//
//  FindViewController.m
//  Shine
//
//  Created by 王斌 on 16/3/9.
//  Copyright © 2016年 王斌. All rights reserved.
//

#import "FindViewController.h"
#import "FindTableViewCell.h"
#import "MJRefresh.h"
@interface FindViewController ()<UITableViewDataSource, UITableViewDelegate>

@property(nonatomic, strong) UITableView *tableView;

@property(nonatomic, strong) NSMutableArray *dataArr;

@property(nonatomic, strong) UITapGestureRecognizer *tap;

@property(nonatomic, strong) UIImageView *bigImageView;

@property(nonatomic, strong) MBProgressHUD *HUD;
@property (nonatomic, strong) MJRefreshLegendHeader *header;
@end

@implementation FindViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.userInteractionEnabled = YES;
    
    self.bigImageView = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH_SCREEN  / 2, 100, 0, 0)];
    self.bigImageView.userInteractionEnabled = YES;
    self.bigImageView.backgroundColor = [UIColor colorWithWhite:0.2 alpha:0.5];

    self.tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapImageView)];
    [self.bigImageView addGestureRecognizer:self.tap];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH_SCREEN, HEIGHT_SCREEN - 113) style:UITableViewStylePlain];
    self.tableView.backgroundColor = COLORBLACK;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
//    self.tableView.rowHeight = 170;
    [self.tableView registerClass:[FindTableViewCell class] forCellReuseIdentifier:@"Findreuse"];
    
    self.header = [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(createData) dateKey:@"find"];
    [self.header beginRefreshing];
}
// 注销MBprogressHUD
-(void)hudWasHidden:(MBProgressHUD *)hud
{
    [self.HUD removeFromSuperview];
    self.HUD = nil;
}


- (void)createData{
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", @"text/plain", @"application/x-javascript", @"application/javascript",nil]];
    [manager.requestSerializer setValue:@"Pacer BAJS0KnUrxCxm2ENF5lTc4TJiOk%3D" forHTTPHeaderField:@"Authorization"];
    [manager GET:@"http://api.dongdong17.com/dongdong/ios/api/v7/checkins?filter=has_note&sort_by=note_score&last_seen_popularity_score=9223372036854775807&limit=10" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        self.dataArr = [NSMutableArray array];
        NSArray *arr = responseObject;
        for (NSInteger i = 0; i < arr.count; i++) {
            NSDictionary *tempDic = arr[i];
            NSDictionary *noteDic = tempDic[@"note"];
            NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
            [dataDic setValue:noteDic[@"note_text"] forKey:@"title"];
            NSArray *imageArr = noteDic[@"images"];
            NSDictionary *temp = [imageArr firstObject];
            [dataDic setValue:temp[@"image_thumbnail_url"] forKey:@"image"];
            [dataDic setValue:temp[@"image_big_url"] forKey:@"bigImage"];
            [self.dataArr addObject:dataDic];

        }
        [self.tableView reloadData];
        [self hudWasHidden:self.HUD];
        [self.header endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"错误信息: %@", error);
        [self hudWasHidden:self.HUD];
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"哎呀~~" message:@"服务器不太给力呢" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *alert = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertController addAction:alert];
        [self presentViewController:alertController animated:YES completion:^{
            
        }];

    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSMutableDictionary *dic = self.dataArr[indexPath.row];
    FindTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Findreuse" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.titleLabel.text = [NSString stringWithFormat:@"%@", dic[@"title"]];
    [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:dic[@"image"]]];
    if ([cell.titleLabel.text isEqualToString:@"<null>"]) {
        cell.titleLabel.text = @"这个人很懒,什么也没写";
    }
    cell.contentView.backgroundColor = COLORBLACK;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSMutableDictionary *dic = self.dataArr[indexPath.row];
    [self.view addSubview:self.bigImageView];
    [self.bigImageView sd_setImageWithURL:[NSURL URLWithString:dic[@"bigImage"]]];
    [UIView animateWithDuration:0.5 animations:^{
        self.bigImageView.frame = CGRectMake(0, 0, WIDTH_SCREEN, HEIGHT_SCREEN - 140);
    }];
}

- (void)tapImageView{
    [UIView animateWithDuration:0.5 animations:^{
        self.bigImageView.frame = CGRectMake(WIDTH_SCREEN / 2, 100, 0, 0);
    }];
}

#pragma mark  设置tableview每行的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    
    // 计算文字的高度
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:17], NSFontAttributeName, nil];
    // 根据文本的内容和文本的字体进行计算高度
    // 参数1:告诉系统,文本显示的最大范围
    CGRect rect = CGRectMake(0, 0, 0, 0);
    NSString *titleStr = self.dataArr[indexPath.row][@"title"];
    if ([titleStr isEqual:[NSNull null]]) {
        rect.size.height = 0;
    }else{
        rect = [self.dataArr[indexPath.row][@"title"] boundingRectWithSize:CGSizeMake(self.view.frame.size.width - 160, 0) options: NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    }
    if (170 > rect.size.height) {
        return 170;
    }else{
        return rect.size.height + 20;
    }

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
